package com.javademo.multithreadingtest;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class SynchronizationTest {
    public static void main(String[] args) throws InterruptedException {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < 100; i++){
            Thread addCountThread = new AddCountThread();
            Thread deleteCountThread = new DeleteCountThread();
            addCountThread.start();
            deleteCountThread.start();
            addCountThread.join();
            deleteCountThread.join();
            if (!map.containsKey(Student.count)){
                map.put(Student.count, 1);
            }else {
                map.put(Student.count, map.get(Student.count) + 1);
            }
        }
        for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
            log.info("key:{}, value:{}", entry.getKey(), entry.getValue());
        }
    }
}

class Student{
    public static Integer count = 0;
    public static final Object lock = new Object();
}

class AddCountThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            synchronized (Student.lock){
                Student.count += 1;
            }
        }
    }
}

class DeleteCountThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            synchronized (Student.lock){
                Student.count -= 1;
            }
        }
    }
}